import csv
import re
import os
import html

class TitleClean:
    def __init__(self, input_filename, output_filename=None):
        self.input_filename = input_filename
        self.output_filename = output_filename if output_filename else f"cleaned_{input_filename}"

    def clean_title(self, title):
        # 解码HTML实体并去除HTML标签
        title = html.unescape(title)
        pattern = re.compile(r'<[^>]+>')
        return re.sub(pattern, '', title)

    def convert_sales(self, sales_str):
        # 提取数字并转换为int类型
        num_str = re.sub(r'[^\d]+', '', sales_str)
        return int(num_str)

    def clean(self):
        # 检查输出文件是否存在，如果不存在则创建
        if not os.path.isfile(self.output_filename):
            with open(self.input_filename, 'r', newline='', encoding='utf-8') as infile, \
                 open(self.output_filename, 'w', newline='', encoding='utf-8') as outfile:
                reader = csv.reader(infile)
                writer = csv.writer(outfile)

                # 读取标题行并清洗
                headers = next(reader)
                cleaned_headers = [self.clean_title(header) for header in headers]
                writer.writerow(cleaned_headers)

                # 遍历CSV中的每一行数据并清洗
                for row in reader:
                    cleaned_title = self.clean_title(row[0])
                    cleaned_sales = self.convert_sales(row[2]) if row[2] else 0
                    row[0] = cleaned_title
                    row[2] = cleaned_sales
                    writer.writerow(row)

            print(f'Data cleaning is complete. Cleaned data is saved to {self.output_filename}')
        else:
            print(f'The output file {self.output_filename} already exists.')


# # 使用示例
# if __name__ == '__main__':
#     # 创建TitleClean对象并调用clean方法
#     # 这里不需要提供绝对路径，只需提供相对于当前工作目录的文件名
#     cleaner = TitleClean('丝毛连衣裙.csv')
#     cleaner.clean()